<template>
  <!-- 坞修 比价单 -->
  <div :class="['PriceComparative', { fullScreen }]" v-if="info">
    <div class="g-con">
      <div class="flexec">
        <el-icon class="icon" @click="fullScreen = !fullScreen"><FullScreen /></el-icon>
      </div>
      <div v-if="!fullScreen" class="head flexec mt-2">
        <!-- <el-button> {{ t('exportPDF') }} </el-button> -->
        <el-button v-if="type !== 'detail'" type="primary" @click="handleSave">
          {{ t('userCenter.b10') }}
        </el-button>
      </div>

      <div class="body mt-2">
        <el-table ref="table1" :data="tableData" style="width: 100%" border scrollbar-always-on>
          <el-table-column v-for="item in tableColumn" :prop="item.prop" :label="item.label" :width="item.width" align="center">
            <template #header v-if="item.isDel">
              {{ item.label }}
              <el-icon @click="handleDel(item.id)" class="ml-1 delete-icon"><CircleCloseFilled /></el-icon>
            </template>
          </el-table-column>
        </el-table>

        <!--  -->
        <el-table ref="table2" :data="tableData2" style="width: 100%" class="mt-2" border scrollbar-always-on>
          <el-table-column :prop="item.prop" :label="item.label" :width="item.width" align="center" v-for="item in tableColumn2" />
        </el-table>

        <!--  -->
        <el-table ref="table3" :data="tableData3" style="width: 100%; display: none" class="mt-2" border scrollbar-always-on>
          <el-table-column :prop="item.prop" :label="item.label" :width="item.width" align="center" v-for="item in tableColumn3" />
        </el-table>

        <div :class="['detail-table', 'mt-2', locale]">
          <el-auto-resizer>
            <template #default="{ height, width }">
              <el-table-v2 ref="table4" :columns="tableColumn4" :data="tableData4" :width="width" :height="height" fixed scrollbar-always-on :row-class="setRowClass" @scroll="scroll">
                <template #row="props">
                  <Row v-bind="props" />
                </template>
              </el-table-v2>
            </template>
          </el-auto-resizer>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount, cloneVNode, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { dockQuoteCompareApi } from '@/service/dockOrder.js'
import { insertShcwComparePriceApi, selectShcwComparePriceByIdApi } from '@/service/common'
import { dateFormat, setItemNumber, amountFormat, getRandomColor } from '@/utils'
import { useI18n } from 'vue-i18n'
import useDict from '@/hooks/useDict'
const { dictData, getDictData, getDictLabel } = useDict()
import Decimal from 'decimal.js'

const router = useRouter()
const route = useRoute()
const { t, locale } = useI18n()

const checkedList = ref(route.query?.checkedList?.split(','))
const orderObjApi = 'shcw_dock_order'
const orderId = ref(null)
const type = ref(route.query.type)
const id = route.query.id

onBeforeMount(() => {
  init()
})
watch(locale, () => {
  init()
})

const fullScreen = ref(false)
watch(fullScreen, (n) => {
  document.body.style.overflow = n ? 'hidden' : ''
})

//
const table1 = ref(null)
const table2 = ref(null)
const table3 = ref(null)
const table4 = ref(null)
onMounted(() => {
  syncScroll()
})
const findTableBody = (dom) => {
  let a, b, c
  a = dom.$refs.bodyWrapper
  b = a.querySelector('.el-scrollbar')
  c = b.querySelector('.el-scrollbar__wrap')
  return c
}
const syncScroll = () => {
  nextTick(() => {
    const table1Body = findTableBody(table1.value)
    const table2Body = findTableBody(table2.value)
    const table3Body = findTableBody(table3.value)

    table1Body.addEventListener('scroll', () => {
      const num = table1Body.scrollLeft
      table2Body.scrollLeft = num
      table3Body.scrollLeft = num
      table4.value.scrollToLeft(num)
    })

    table2Body.addEventListener('scroll', () => {
      const num = table2Body.scrollLeft
      table1Body.scrollLeft = num
      table3Body.scrollLeft = num
      table4.value.scrollToLeft(num)
    })

    table3Body.addEventListener('scroll', () => {
      const num = table3Body.scrollLeft
      table1Body.scrollLeft = num
      table2Body.scrollLeft = num
      table4.value.scrollToLeft(num)
    })
  })
}
const scroll = ({ xAxisScrollDir, scrollLeft, yAxisScrollDir, scrollTop }) => {
  const table1Body = findTableBody(table1.value)
  const table2Body = findTableBody(table2.value)
  const table3Body = findTableBody(table3.value)
  table1Body.scrollLeft = scrollLeft
  table2Body.scrollLeft = scrollLeft
  table3Body.scrollLeft = scrollLeft
}

//
const tableColumn = ref([])
const tableData = ref([])
const setTableData = () => {
  tableData.value = [
    {
      'prop-0': t('DockOrderOnlineQuotation.t9')
    },
    {
      'prop-0': t('DockOrderOnlineQuotation.sm_l1')
    },
    {
      'prop-0': t('DockOrderOnlineQuotation.sm_l2')
    },
    {
      'prop-0': t('DockOrderOnlineQuotation.sm_l3')
    },
    {
      'prop-0': t('DockOrderOnlineQuotation.sm_l4')
    },
    {
      'prop-0': t('DockOrderOnlineQuotation.sm_l5')
    },
    // {
    //   'prop-0': t('DockOrderOnlineQuotation.t17')
    // },
    {
      'prop-0': t('DockOrderOnlineQuotation.t48')
    }
  ]
}

const tableColumn2 = ref([])
const tableData2 = ref([])

const tableColumn3 = ref([])
const tableData3 = ref([])

const tableColumn4 = ref([])
const tableData4 = ref([])
const mapListLen = ref(0)
const initColLen = ref(0)

const quoteOrderCurrency = ref('')
const processTrycatch = (jsonStr) => {
  let obj = null
  try {
    obj = JSON.parse(jsonStr)
  } catch (e) {
    obj = jsonStr
    return obj
  }
}
// 获取数据
const info = ref({})
const getData = () => {
  dockQuoteCompareApi({
    idList: checkedList.value,
    orderObjApi
  }).then(({ data }) => {
    info.value = data
    const {
      baseQuotaInfo,
      aggregateVoListMap,
      importancePriceInfo,
      dockQuoteCompareDetailVo: { mapList, shcwDockOrderDetails }
    } = data

    // 报价说明
    const col1 = []
    baseQuotaInfo.forEach((item, index) => {
      let obj = {}
      if (index === 0) {
        obj = {
          label: item.dockOrderName,
          prop: `prop-${index}`,
          width: 700
        }
        orderId.value = item.id
        quoteOrderCurrency.value = item.quoteOrderCurrency
      } else {
        obj = {
          label: item.enterpriseName,
          prop: `prop-${index}`,
          isDel: baseQuotaInfo.length > 2 && type.value !== 'detail',
          id: item.id,
          width: checkedList.value.length >= 2 ? 280 : 560
        }

        tableData.value.forEach((d, i) => {
          if (i === 0) {
            d[`prop-${index}`] = t('DockOrderOnlineQuotation.t25')
          } else if (i === 1) {
            const statementRepairPeriod = item.statementRepairPeriod?.split(',')
            d[`prop-${index}`] = statementRepairPeriod ? `${t('DockOrderOnlineQuotation.default.s1-1')}${statementRepairPeriod[0]}${t('DockOrderOnlineQuotation.default.s1-2')}${statementRepairPeriod[1]}${t('DockOrderOnlineQuotation.default.s1-3')}${statementRepairPeriod[2]}${t('DockOrderOnlineQuotation.default.s1-4')}` : ''
          } else if (i === 2) {
            d[`prop-${index}`] = `${t('DockOrderOnlineQuotation.default.s2')}`
          } else if (i === 3) {
            const statementPayment = item.statementPayment?.split(',')
            d[`prop-${index}`] = statementPayment ? `${statementPayment[0]}${t('DockOrderOnlineQuotation.default.s3-1')}${statementPayment[1]}${t('DockOrderOnlineQuotation.default.s3-2')}${statementPayment[2]}${t('DockOrderOnlineQuotation.default.s3-3')}` : ''
          } else if (i === 4) {
            const statementDelayPenalty = item.statementDelayPenalty?.split(',')
            d[`prop-${index}`] = statementDelayPenalty ? `${t('DockOrderOnlineQuotation.default.s4-1')}${statementDelayPenalty[0]}${t('DockOrderOnlineQuotation.default.s4-2')}${statementDelayPenalty[1]}${t('DockOrderOnlineQuotation.default.s4-3')}` : ''
          } else if (i === 5) {
            d[`prop-${index}`] = item.statementValidity ? `${t('DockOrderOnlineQuotation.default.s5-1')}${item.statementValidity}${t('DockOrderOnlineQuotation.default.s5-2')}` : ''
          } else if (i === 6) {
            d[`prop-${index}`] = item.quoteDescription
          }
        })
      }
      col1.push(obj)
    })
    tableColumn.value = col1

    // 项目汇总
    const col2 = [
      {
        label: t('DockOrderOnlineQuotation.t19'),
        prop: `prop-0`,
        width: 700,
        align: 'center'
      }
    ]
    const aggregateVoList = JSON.parse(aggregateVoListMap)

    Object.keys(aggregateVoList).forEach((key, index) => {
      const value = aggregateVoList[key]
      if (index === 0) {
        value.forEach((item, i) => {
          col2.push({
            label: t('DockOrderOnlineQuotation.t20'),
            prop: `prop-0-${i}`,
            width: checkedList.value.length >= 2 ? 280 : 560,
            align: 'center'
          })
        })
      }

      tableData2.value[index] = {}
      tableData2.value[index][`prop-0`] = value.find((item) => item.projectName)?.projectName

      value.forEach((item, i) => {
        tableData2.value[index][`prop-0-${i}`] = item.projectNameCn === '优惠' ? `${item.feeSummary}%` : amountFormat(item.feeSummary)
      })
    })
    tableColumn2.value = col2

    // 重要单价
    // let col3 = [
    //   {
    //     label: t('DockOrderOnlineQuotation.t22'),
    //     prop: `prop-0`,
    //     width: 350,
    //     align: 'center'
    //   },
    //   {
    //     label: t('DockOrderOnlineQuotation.t23'),
    //     prop: `prop-1`,
    //     width: 350,
    //     align: 'center'
    //   }
    // ]
    // Object.keys(importancePriceInfo).forEach((key, index) => {
    //   const value = importancePriceInfo[key]

    //   if (index === 0) {
    //     value.forEach((item, i) => {
    //       col3 = [
    //         ...col3,
    //         ...[
    //           {
    //             label: t('DockOrderOnlineQuotation.t24'),
    //             prop: `prop-0-${i}`,
    //             width: checkedList.value.length >= 2 ? 140 : 560 / 2,
    //             align: 'center'
    //           },
    //           {
    //             label: t('DockOrderOnlineQuotation.t25'),
    //             prop: `prop-1-${i}`,
    //             width: checkedList.value.length >= 2 ? 140 : 560 / 2,
    //             align: 'center'
    //           }
    //         ]
    //       ]
    //     })
    //   }

    //   tableData3.value[index] = {}
    //   tableData3.value[index][`prop-0`] = value.find((item) => item.importanceType).importanceType
    //   tableData3.value[index][`prop-1`] = value.find((item) => item.unit).unit

    //   value.forEach((item, i) => {
    //     tableData3.value[index][`prop-0-${i}`] = item.importancePrice
    //     tableData3.value[index][`prop-1-${i}`] = item.projectContent
    //   })
    // })
    // tableColumn3.value = col3

    // 坞修明细
    getCol4Data()
    mapList.forEach((item, index) => {
      const colum = [
        {
          title: t('userCenter.price'), //
          key: `prop-0-${index}`,
          dataKey: `prop-0-${index}`,
          width: checkedList.value.length >= 2 ? 280 / 4 : 280 / 2,
          align: 'center',
          cellRenderer: ({ rowData, rowIndex }) => {
            return rowIndex !== tableData4.value.length - 1 ? amountFormat(rowData[`prop-0-${index}`]) : rowData[`prop-0-${index}`]
          }
        },
        {
          title: t('userCenter.discount'), //
          key: `prop-1-${index}`,
          dataKey: `prop-1-${index}`,
          width: checkedList.value.length >= 2 ? 280 / 4 : 280 / 2,
          align: 'center'
        },
        {
          title: t('userCenter.amount'),
          key: `prop-2-${index}`,
          dataKey: `prop-2-${index}`,
          width: checkedList.value.length >= 2 ? 280 / 4 : 280 / 2,
          align: 'center',
          cellRenderer: ({ rowData, rowIndex }) => {
            return amountFormat(rowData[`prop-2-${index}`])
          }
        },
        {
          title: t('userCenter.remark'), //
          key: `prop-3-${index}`,
          dataKey: `prop-3-${index}`,
          width: checkedList.value.length >= 2 ? 280 / 4 : 280 / 2,
          align: 'center'
        }
      ]
      tableColumn4.value = [...tableColumn4.value, ...colum]
    })

    shcwDockOrderDetails.forEach((item, index) => {
      mapList.forEach((m, i) => {
        item[`prop-0-${i}`] = m[item.id].price
        item[`prop-1-${i}`] = m[item.id].discount ? m[item.id].discount + '%' : m[item.id].discount
        item[`prop-2-${i}`] = m[item.id].amount || null
        item[`prop-3-${i}`] = m[item.id].remark
      })
    })

    // 合计
    // const lastObj = {}
    // mapList.forEach((m, i) => {
    //   let total = Decimal(0)
    //   shcwDockOrderDetails.forEach((item) => {
    //     total = total.add(Decimal(item[`prop-2-${i}`] || 0))
    //   })
    //   lastObj[`prop-0-${i}`] = `${t('userCenter.total')}: ${amountFormat(Number(total))} ${dictData.value['currency']?.find((item) => item.dictValue === quoteOrderCurrency.value)?.dictLabel || ''}`
    // })
    // shcwDockOrderDetails.push(lastObj)

    tableData4.value = shcwDockOrderDetails
    setItemNumber(shcwDockOrderDetails)

    mapListLen.value = mapList.length
  })
}

// 行 class
const setRowClass = ({ columns, rowData, rowIndex }) => {
  // console.log(columns, rowData, rowIndex, '---')
  let str = ''

  if (rowData.projectLevel !== null) {
    str += ` projectLevel-${rowData.projectLevel}`
  }

  return str
}

const colorArr = ref([])

// cell
const Row = ({ rowData, rowIndex, cells, columns }) => {
  
  // 背景色
  let backgroundColor = ''
  for (let index = initColLen.value; index < initColLen.value + mapListLen.value * 4; index++) {
    if (!colorArr.value.some((item) => item.index === index)) {
      colorArr.value.push({
        index,
        color: getRandomColor(0.16)
      })
    }

    if ((index - initColLen.value) % 4 === 0) {
      backgroundColor = colorArr.value.find((item) => item.index === index).color
    }

    if (!cells[index]) return
    const style = {
      ...cells[index].props.style,
      backgroundColor
    }

    cells[index] = cloneVNode(cells[index], { style })
  }

  // 比较
  const amountArr = []
  for (let index = 0; index < mapListLen.value; index++) {
    amountArr.push({
      key: `prop-2-${index}`,
      value: rowData[`prop-2-${index}`]
    })
  }

  amountArr.sort((a, b) => {
    return a.value - b.value
  })

  if (amountArr[0].value === null || amountArr[0].value === amountArr[1]?.value) return cells

  const colSpanIndex = columns.findIndex((item) => item.key === amountArr[0].key)
  const style = {
    ...cells[colSpanIndex].props.style,
    backgroundColor: '#F8CD95'
  }

  cells[colSpanIndex] = cloneVNode(cells[colSpanIndex], { style })

  // 合并列
  if (rowIndex === tableData4.value.length - 1) {
    let colSpanIndex = 0
    for (let index = 0; index <= mapListLen.value; index++) {
      if (!cells[colSpanIndex]) return
      let width = Number.parseInt(cells[colSpanIndex].props.style.width)

      for (let i = 1; i < (index === 0 ? initColLen.value : 4); i++) {
        width += Number.parseInt(cells[colSpanIndex + i].props.style.width)
        cells[colSpanIndex + i] = null
      }

      const style = {
        ...cells[colSpanIndex].props.style,
        width: `${width}px`
      }
      cells[colSpanIndex] = cloneVNode(cells[colSpanIndex], { style })
      colSpanIndex = initColLen.value + 4 * index
    }
  }

  return cells
}

// 删除一个 报价
const handleDel = (id) => {
  checkedList.value = checkedList.value.filter((item) => item != id)
  init()
}

// 保存比价单
const handleSave = () => {
  insertShcwComparePriceApi({
    idList: checkedList.value,
    orderObjApi,
    orderId: orderId.value
  }).then(({ msg }) => {
    ElMessage.success(msg)
  })
}

// 坞修明细表头
const getCol4Data = () => {
  tableColumn4.value = [
    {
      title: t('dockRepair.coltit1'), // 项目编号
      key: 'itemNumber',
      dataKey: 'itemNumber',
      width: 100,
      class: 'itemNumber',
      align: 'center'
    },
    {
      title: t('dockRepair.coltit2'), // 项目类型
      key: 'projectName',
      dataKey: 'projectName',
      width: 400,
      cellRenderer: ({ rowData, rowIndex }) => {
        return `${rowData.projectName} ${rowData.projectContent || ''}`
      }
    },
    {
      title: t('dockRepair.coltit4'), // 单位
      key: 'unit',
      dataKey: 'unit',
      width: 100,
      align: 'center'
    },
    {
      title: t('dockRepair.coltit5'), // 数量
      key: 'requireCount',
      dataKey: 'requireCount',
      width: 100,
      align: 'center'
    }
    // {
    //   title: t('dockRepair.coltit3'), // 项目类型说明
    //   key: 'projectContent',
    //   dataKey: 'projectContent',
    //   width: 100,
    //   align: 'center',
    //   cellRenderer: ({ rowData, rowIndex }) => {
    //     return rowData.projectContent
    //   }
    // }
  ]
  initColLen.value = tableColumn4.value.length
}

// 回显 idList
const getDetail = async () => {
  await selectShcwComparePriceByIdApi({
    id
  }).then(({ data: { idList } }) => {
    checkedList.value = idList
  })
}

// init
const init = async () => {
  if (type.value === 'detail') {
    await getDetail()
  }
  await getDictData('currency')
  setTableData()
  getData()
}
</script>

<style scoped lang="scss">
.PriceComparative {
  background: #f5f5f5;
  padding: 30px 0;
  margin-bottom: -76px;

  &.fullScreen {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    overflow: auto;
    z-index: 99999;
    margin-bottom: 0;
    .g-con {
      width: calc(100% - 20px);
    }
  }

  .icon {
    cursor: pointer;
  }

  .el-button {
    min-width: 140px;
  }

  .delete-icon {
    cursor: pointer;
    font-size: 20px;
  }

  .detail-table {
    height: 700px;

    :deep(.el-table-v2__header-cell) {
      background: #f0f3f8;
      color: #252628;
    }
    :deep(.no-save) {
      background: #f9ecd9;
    }
    :deep(.projectLevel-0) {
      background: #f7f9fb;
    }

    :deep(.projectLevel-0),
    :deep(.projectLevel-1),
    :deep(.projectLevel-2) {
      .itemNumber {
        justify-content: center;
      }
    }
    :deep(.projectLevel-3),
    :deep(.projectLevel-4) {
      .itemNumber {
        justify-content: right;
      }
    }

    // &.en {
    :deep(.el-table-v2__header-cell) {
      font-family: 'Sitka Display Semibold';
      padding: 0;
      * {
        font-size: 13px;
      }
    }

    :deep(.projectLevel-0) {
      font-family: 'Amasis MT Pro Medium';
      * {
        font-size: 17px;
        font-weight: bold;
      }
    }
    :deep(.projectLevel-1) {
      font-family: '等线';
      * {
        font-size: 16px;
        font-weight: bold;
      }
    }

    :deep(.projectLevel-2, .projectLevel-3, .projectLevel-4) {
      font-family: 'Abadi';
      * {
        font-size: 15px;
      }
    }
    // }
  }
}
</style>
